package cn.lhn.ridersclub.service;

import cn.lhn.ridersclub.entity.Account;
import cn.lhn.ridersclub.entity.BlackList;
import cn.lhn.ridersclub.mapper.AccountMapper;
import cn.lhn.ridersclub.mapper.BlacklistMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class BlacklistServiceImpl implements BlacklistService {

    private final BlacklistMapper blacklistMapper;

    private final AccountMapper accountMapper;

    public BlacklistServiceImpl(BlacklistMapper blacklistMapper, AccountMapper accountMapper) {
        this.blacklistMapper = blacklistMapper;
        this.accountMapper = accountMapper;
    }

    @Override
    public void add(Long sourceId, Long targetId) {
        //  判断账号是否存在
        if (accountMapper.selectById(sourceId) == null) {
            throw new RuntimeException("账号不存在");
        }
        if (accountMapper.selectById(targetId) == null) {
            throw new RuntimeException("目标账号不存在");
        }

        //  判断是否已存在
        if (isBlack(sourceId, targetId)) {
            throw new RuntimeException("请勿重复添加");
        }

        //  添加数据
        int i = blacklistMapper.insert(new BlackList(0L, sourceId, targetId));
        if (i == 0) {
            throw new RuntimeException("添加失败");
        }
    }

    @Override
    public void delete(Long sourceId, Long targetId) {
        QueryWrapper<BlackList> qw = new QueryWrapper<>();
        qw.eq("source_id", sourceId);
        qw.eq("target_id", targetId);
        int i = blacklistMapper.delete(qw);
        if (i == 0) {
            throw new RuntimeException("删除失败");
        }
    }

    @Override
    public boolean isBlack(Long sourceId, Long targetId) {
        QueryWrapper<BlackList> qw = new QueryWrapper<>();
        qw.eq("source_id", sourceId);
        qw.eq("target_id", targetId);
        return blacklistMapper.selectOne(qw) != null;
    }

    @Override
    public List<Account> listBlack(Long sourceId) {
        QueryWrapper<BlackList> qw = new QueryWrapper<>();
        qw.eq("source_id", sourceId);
        List<BlackList> blackList = blacklistMapper.selectList(qw);
        List<Account> list = new ArrayList<>();
        for (BlackList black : blackList) {
            list.add(accountMapper.selectById(black.getTargetId()));
        }
        return list;
    }
}
